<template>
    <div class="shawbs-form-item">
        <slot />
        <div class="shawbs-form-error" v-if="error">{{error}}</div>
    </div>
</template>

<script>
    export default {
        name: 'ShawbsFormItem',
        props: {
            prop: String
        },
        data(){
            return {
                error: '',
                status: 1, // 1默认 2有效 3无效
                form: null,
            }
        },
        mounted(){
            this.form = this.getForm()
            this.form.fields.push(this)
        },
        methods: {
            getForm  ()  {
                let parent = this.$parent
                while (parent && parent.name !== 'shawbsForm') {
                    parent = parent.parent
                }
                return parent
            },
            check() {
                const rules = this.form.rules ? this.form.rules[this.prop] || [] : []
                if (rules.length === 0) {
                    this.status = 2
                    this.error = ''
                }
                const value = this.form.model[this.prop]
                for(let item of rules){ 
                    if (item.require && value === '') {
                        this.status = 3
                        this.error = item.message || '该值为必填'
                        break
                    }
                    if (item.reg && RegExp(item.reg).test(value) === false) {
                        this.status = 3
                        this.error = item.message || '该值无效'
                        break
                    }
                    if (item.handle && typeof item.handle === 'function') {
                        const msg = item.handle(value) // 返回错误信息，无则有效，有则无效
                        if (msg) {
                            this.status = 3
                            this.error = msg
                        } else {
                            this.status = 2
                            this.error = ''
                        }
                        break
                    }
                    this.status = 2
                    this.error = ''
                }
                return this.status === 2
            }
        }

    }
</script>

<style>
.shawbs-form-error{
    text-align: left;
    color: rgb(224, 24, 24);
}
</style>